package com.ruoyi.web.controller.walmart;

import org.apache.commons.codec.binary.Hex;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/webhook")
public class WebhookController {

    private static final String WALMART_SECRET_KEY = "7c48b0e7-2cc0-4479-b03e-1b99721d2d20"; // 您在沃尔玛开发者中心获取的密钥

    // 处理POST请求，接收沃尔玛推送的通知
    @PostMapping
    public ResponseEntity<String> handleWebhook(@RequestBody String body, @RequestHeader("X-WALMART-SIGNATURE") String signature) {
        // 验证签名，确保通知来自沃尔玛
        if (!verifySignature(body, signature)) {
            return ResponseEntity.status(400).body("Invalid signature");
        }

        // 处理Webhook的业务逻辑
        System.out.println("Received Webhook: " + body);

        // 这里可以添加代码来解析接收到的数据，并做进一步处理

        return ResponseEntity.ok("Notification received successfully");
    }

    // 验证沃尔玛推送的签名
    private boolean verifySignature(String requestBody, String receivedSignature) {
        String computedSignature = computeSignature(requestBody);
        return computedSignature.equals(receivedSignature);
    }

    // 使用HMAC-SHA256计算签名
    private String computeSignature(String requestBody) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(WALMART_SECRET_KEY.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(secretKeySpec);
            byte[] rawHmac = mac.doFinal(requestBody.getBytes(StandardCharsets.UTF_8));
            return Hex.encodeHexString(rawHmac);  // 转换为十六进制字符串
        } catch (Exception e) {
            throw new RuntimeException("Error computing signature", e);
        }
    }
}

